﻿
using SuperSocialShare.Authorize;
using SuperSocialShare.Error;
using SuperSocialShare.Helper;
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
namespace SuperSocialShare.Clients
{
    /// <summary>
    /// 网易微博分享客户端
    /// </summary>
    public class NetEaseClient : SocialClient
    {
        protected override string AuthorizeUrl
        {
            get { return "https://api.t.163.com/oauth2/authorize"; }
        }

        protected override string GetAccessTokenUrl
        {
            get { throw new NotImplementedException(); }
        }

        protected override string GetUserInfoUrl
        {
            get { return "https://api.t.163.com/users/show.json"; }
        }

        protected override string UpdateStatusUrl
        {
            get { return "https://api.t.163.com/statuses/update.json"; }
        }

        protected override string UploadImageUrl
        {
            get { return "https://api.t.163.com/statuses/upload.json"; }
        }

        protected override string RevokeAuthorizeUrl
        {
            get { throw new NotImplementedException(); }
        }

        public override SocialType SocialType
        {
            get { return SocialType.NetEase; }
        }

        internal override string GetRequestAuthorizeUrl()
        {
            Dictionary<string, object> parameters = new Dictionary<string, object>() 
            {
                {"client_id",ClientId},
                {"client_secret",ClientSecret},
                {"display","mobile"},
                {"response_type","token"},
                {"redirect_uri",CallbackUrl}
            };
            return Utility.BuildQueryString(AuthorizeUrl, parameters);
        }

        protected override void GetUserInfoAsync(AuthorizeInfo info)
        {
            HttpWebRequester requester = new HttpWebRequester();
            requester.Parameters.Add(new RequestParameter("access_token", info.AccessToken));
            requester.RequestCompleted += requester_RequestCompleted;
            requester.BeginRequest(GetUserInfoUrl, 0);
        }

        internal override void ProcessResponseDataOfAuthorize(string data)
        {
            NetEaseAuthorizeInfo authorizeInfo = new NetEaseAuthorizeInfo();
            authorizeInfo.AccessToken = Utility.GetRegexContent(@"(?<=access_token=)[^&]*", data);
            authorizeInfo.Expires = Convert.ToInt32(Utility.GetRegexContent(@"(?<=expires_in=)[^&]*", data));
            AuthorizeManager.Save(authorizeInfo, SocialType);
            GetUserInfoAsync(authorizeInfo);
        }

        public override void RevokeAuthorizeAysnc()
        {
            throw new NotImplementedException();
        }

        public override void ShareText(string text)
        {
            NetEaseAuthorizeInfo authorizeInfo = AuthorizeManager.GetAuthorizeInfo(SocialType) as NetEaseAuthorizeInfo;
            if (authorizeInfo != null)
            {
                HttpWebRequester requester = new HttpWebRequester();
                requester.PostContentType = ContentType.APPLICATION_X_WWW_FORM_URLENCODED;
                requester.Parameters.Add(new RequestParameter("status", text));
                requester.Parameters.Add(new RequestParameter("access_token", authorizeInfo.AccessToken));
                requester.RequestCompleted += requester_RequestCompleted;
                requester.BeginRequest(UpdateStatusUrl, 1, "POST");
            }
        }

        public override void ShareTextWithImage(string text, byte[] imgdata)
        {
            NetEaseAuthorizeInfo authorizeInfo = AuthorizeManager.GetAuthorizeInfo(SocialType) as NetEaseAuthorizeInfo;
            if (authorizeInfo != null)
            {
                HttpWebRequester requester = new HttpWebRequester();
                requester.PostContentType = ContentType.MULTIPART_FORM_DATA;
                requester.Parameters.Add(new RequestParameter("pic", imgdata));
                requester.Parameters.Add(new RequestParameter("access_token", authorizeInfo.AccessToken));

                requester.RequestCompleted += e =>
                {
                    /*
                     * 网易微博发布带图片的微博的方式为：
                     * 先上传图片，得到图片的服务器地址后，将地址添加大要发布的文本中，
                     * 再调用status/update接口发布微博
                     */
                    AsyncEventArgs args = new AsyncEventArgs();
                    if (e.Error == null)
                    {
                        string tag = "upload_image_url";
                        if (e.Result.Contains(tag))//返回数据为上传后的图片地址 
                        {
                            string pattern = @"(?<=""" + tag + @"""[\s\S]*?:[\s\S]*?"").*?(?="")";
                            string imgUrl = Utility.GetRegexContent(pattern, e.Result);
                            if (!string.IsNullOrEmpty(imgUrl))
                                text += imgUrl;
                            ShareText(text);
                        }
                    }
                    else
                    {
                        args.Error = new Error.ErrorBase(e.Error);
                        OnShareCompleted(args);
                    }
                };
                requester.BeginRequest(UploadImageUrl, "POST");
            }
        }

        void requester_RequestCompleted(RequestCompletedEventArgs e)
        {
            AsyncEventArgs args = new AsyncEventArgs();
            int actionTag = Convert.ToInt32(e.UserData);
            if (e.Error == null)
            {
                ErrorBase error = JsonConverter.GetObjectFromJsonString<ErrorBase>(e.Result);
                if (error != null && error.ErrorCode != 0)
                {
                    args.Error = error;
                }

                if (actionTag == 0)//获取用户信息的返回数据
                {
                    NetEaseAuthorizeInfo authorizeInfo = AuthorizeManager.GetAuthorizeInfo(SocialType) as NetEaseAuthorizeInfo;
                    if (authorizeInfo != null)
                    {
                        UserInfo user = new UserInfo();
                        user.Fill(e.Result, SocialType);
                        authorizeInfo.UserInfo = user;
                        args.Result = authorizeInfo;
                    }
                    OnGetAuthorizeInfoCompleted(args);
                }
                else//分享后的返回数据
                {
                    OnShareCompleted(args);
                }
            }
            else//发生WebException
            {
                args.Error = new Error.ErrorBase(e.Error);
                if (actionTag == 0)
                {
                    OnGetAuthorizeInfoCompleted(args);
                }
                else
                {
                    OnShareCompleted(args);
                }
            }
        }
    }
}
